package com.weitu.contractor.controller;

import com.weitu.accessory.service.AccessoryUtilService;
import com.weitu.accessory.util.AccessoryUtil;
import com.weitu.base.annotaion.SystemLog;
import com.weitu.base.controller.BaseController;
import com.weitu.contractor.entity.ContractorExposure;
import com.weitu.contractor.entity.ContractorExposureCriteria;
import com.weitu.contractor.service.ContractorAuditService;
import com.weitu.contractor.service.ContractorExposureService;
import com.weitu.paging.DataGridPagination;
import com.weitu.plugin.PageView;
import com.weitu.util.AjaxResult;
import com.weitu.util.DateTimeUtil;
import com.weitu.util.IDGenerator;
import com.weitu.workflow.definition.constant.FlowDefConstants;
import com.weitu.workflow.flowBusiness.constant.FlowBusinessConstants;
import com.weitu.workflow.flowManagement.entity.WorkflowReview;
import com.weitu.workflow.flowManagement.service.FlowManagementService;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.fireflow.kernel.KernelException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.weitu.util.AjaxResult.fail;
import static com.weitu.util.AjaxResult.success;

/**
 * @author LiMeng 2017/4/15
 */
@Controller
@RequestMapping(value = "/contractor/contractorExposure")
public class ContractorExposureController extends BaseController {
    private static final String MODULE_BATH_PATH = BASE_JSP_PATH + "contractor/contractorExposure";
    private final ContractorExposureService contractorExposureService;
    private final ContractorAuditService contractorAuditService;
    private final FlowManagementService flowManagementService;
    private final AccessoryUtilService accessoryUtilService;

    @Autowired
    public ContractorExposureController(ContractorExposureService contractorExposureService
            , ContractorAuditService contractorAuditService
            , FlowManagementService flowManagementService
            , AccessoryUtilService accessoryUtilService) {
        this.contractorExposureService = contractorExposureService;
        this.contractorAuditService = contractorAuditService;
        this.flowManagementService = flowManagementService;
        this.accessoryUtilService = accessoryUtilService;
    }

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list() {
        return MODULE_BATH_PATH + "/list";
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add(Model model) {
        model.addAttribute("loginUserId", getSessionUser().getId());
        model.addAttribute("loginUserName", getSessionUser().getRealName());
        model.addAttribute("today", DateFormatUtils.ISO_DATE_FORMAT.format(new Date()));
        return MODULE_BATH_PATH + "/add";
    }

    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Model model, String id) {
        if (StringUtils.isNotEmpty(getPara("businessId"))) {
            id = getPara("businessId");
            WorkflowReview workflowReview = this.flowManagementService.queryWorkflowReviewByWorkItemId(getPara("workItemId"));
            model.addAttribute("workflowReview", workflowReview);
        }
        model.addAttribute("accessoryList", accessoryUtilService.queryAccessoryByBusinessId(id));
        model.addAttribute("contractorExposure", contractorExposureService.selectByPrimaryKey(id));
        model.addAttribute("loginUserId", getSessionUser().getId());
        return MODULE_BATH_PATH + "/edit";
    }

    @RequestMapping(value = "/view", method = RequestMethod.GET)
    public String view(Model model, String id) {
        model.addAttribute("accessoryList", accessoryUtilService.queryAccessoryByBusinessId(id));
        model.addAttribute("contractorExposure", contractorExposureService.selectByPrimaryKey(id));
        model.addAttribute("loginUserId", getSessionUser().getId());
        return MODULE_BATH_PATH + "/edit";
    }

    @ResponseBody
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public Object listAjax(HttpServletRequest request, String sort) throws Exception {
        ContractorExposureCriteria example = new ContractorExposureCriteria();
        ContractorExposureCriteria.Criteria criteria = example.createCriteria().andDelStateEqualTo(0);
        putSearchCriteria(criteria);

        int count = contractorExposureService.countByCriteria(example);

        DataGridPagination dataGridPagination = DataGridPagination.getInstance(request, count);//获取分页对象
        PageView pageView = dataGridPagination.getPageView();//生成pageView分页对象
        //未传sort参数是采用添加时间排序
        if (StringUtils.isEmpty(sort)) {
            pageView.setSortColumn("addTime");
        } else {
            example.setOrderByClause(pageView.getSortColumn() + " " + pageView.getOrderType());
        }
        example.setPageView(pageView);

        List<ContractorExposure> contractorExposures = contractorExposureService.selectByCriteria(example);

        return dataGridPagination.flushDataGridData(contractorExposures);
    }

    @SystemLog(module = "承包商曝光台", methods = "新增承包商曝光台信息")
    @ResponseBody
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public AjaxResult addAjax(ContractorExposure contractorExposure) throws Exception {
        if (contractorExposureService.checkIfExist(contractorExposure.getContractorAuditId(), contractorExposure.getExposureEndDate())) {
            return fail("曝光时间内已有该承包商，请重新选择！");
        }
        String id = IDGenerator.getId();
        contractorExposure.setId(id);
        contractorExposure.setAddUserId(getSessionUser().getId());
        contractorExposure.setAddDeptId(getSessionUser().getDepartment().getId());
        contractorExposure.setAddTime(DateTimeUtil.formatterDateTime());
        if (AccessoryUtil.saveAccerssoryInfo(id)) {
            if (contractorExposureService.insertSelective(contractorExposure) > 0) {
                return success("保存成功！", contractorExposure);
            }
            return fail("保存失败！");
        }
        return fail("附件信息保存失败！");
    }

    @SystemLog(module = "承包商曝光台", methods = "更新承包商曝光台信息")
    @ResponseBody
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @Transactional
    public AjaxResult editAjax(ContractorExposure contractorExposure) throws Exception {
        if (contractorExposureService.checkIfExist(contractorExposure.getContractorAuditId(),
                contractorExposure.getExposureEndDate(),
                contractorExposure.getId())) {
            return fail("该承包商已在曝光台，请重新选择！");
        }
        contractorExposure.setUpdateUserId(getSessionUser().getId());
        contractorExposure.setUpdateDeptId(getSessionUser().getDepartment().getId());
        contractorExposure.setUpdateTime(DateTimeUtil.formatterDateTime());
        if (AccessoryUtil.saveAccerssoryInfo(contractorExposure.getId())) {
            if (contractorExposureService.updateByPrimaryKeySelective(contractorExposure) > 0) {
                return success("保存成功！", contractorExposure);
            }
            return fail("保存失败！");
        }
        return fail("附件信息保存失败！");

    }

    @SystemLog(module = "承包商曝光台", methods = "删除承包商曝光台信息")
    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public AjaxResult deleteAjax(String id) throws Exception {
        if (contractorExposureService.deleteByPrimaryKey(id) > 0) {
            return success("删除成功！");
        } else {
            return fail("删除失败！");
        }
    }

    @SystemLog(module = "年度评价", methods = "提交年度评价审核信息")
    @ResponseBody
    @RequestMapping(value = "/submit", method = RequestMethod.POST)
    public AjaxResult submitAjax(ContractorExposure contractorExposure, String nextUserId) throws Exception {
        if (contractorExposureService.checkIfExist(contractorExposure.getContractorAuditId(),
                contractorExposure.getExposureEndDate(),
                contractorExposure.getId())) {
            return fail("该承包商已在曝光台，请重新选择！");
        }
        contractorExposure.setUpdateUserId(getSessionUser().getId());
        contractorExposure.setUpdateDeptId(getSessionUser().getDepartment().getId());
        contractorExposure.setUpdateTime(DateTimeUtil.formatterDateTime());
        contractorExposure.setAuditState(1);
        if (AccessoryUtil.saveAccerssoryInfo(contractorExposure.getId())) {
            if (contractorExposureService.updateByPrimaryKeySelective(contractorExposure) > 0) {
                handleFlowStart(contractorExposure, nextUserId);
                return success("提交成功！", contractorExposure);
            }
            return fail("提交失败！");
        }
        return fail("附件信息保存失败！");
    }

    @SystemLog(module = "年度评价", methods = "审核年度评价信息")
    @ResponseBody
    @RequestMapping(value = "/audit", method = RequestMethod.POST)
    public AjaxResult auditAjax(HttpServletRequest request) throws Exception {
        if (handleFlowEnd(request)) {
            return success("审批成功！");
        }
        return fail("审批失败！");
    }

    /**
     * 添加查询条件
     *
     * @param criteria 条件
     */
    private void putSearchCriteria(ContractorExposureCriteria.Criteria criteria) {
        if (StringUtils.isNotEmpty(getPara("contractorName"))) {
            List<String> contractorAuditIds = contractorAuditService.selectContractorAuditIdsByName(getPara("contractorName"));
            if (!contractorAuditIds.isEmpty()){
                criteria.andContractorAuditIdIn(contractorAuditIds);
            }else {
                criteria.andIdIsNull();
            }
        }
        if (StringUtils.isNotEmpty(getPara("applicantId"))) {
            criteria.andApplicantIdEqualTo(getPara("applicantId"));
        }
        if (StringUtils.isNotEmpty(getPara("exposureEndDateMin"))) {
            criteria.andExposureEndDateGreaterThanOrEqualTo(getPara("exposureEndDateMin"));
        }
        if (StringUtils.isNotEmpty(getPara("exposureEndDateMax"))) {
            criteria.andExposureEndDateLessThanOrEqualTo(getPara("exposureEndDateMax"));
        }
        if (StringUtils.isNotEmpty(getPara("addTimeMin"))) {
            criteria.andAddTimeGreaterThanOrEqualTo(getPara("addTimeMin"));
        }
        if (StringUtils.isNotEmpty(getPara("addTimeMax"))) {
            criteria.andAddTimeLessThanOrEqualTo(getPara("addTimeMax"));
        }
        if (StringUtils.isNotEmpty(getPara("applicantDateMin"))) {
            criteria.andApplicantDateGreaterThanOrEqualTo(getPara("applicantDateMin"));
        }
        if (StringUtils.isNotEmpty(getPara("applicantDateMax"))) {
            criteria.andApplicantDateLessThanOrEqualTo(getPara("applicantDateMax"));
        }
        if (StringUtils.isNotEmpty(getPara("addUserId"))) {
            criteria.andAddUserIdEqualTo(getPara("addUserId"));
        }
        if (StringUtils.isNotEmpty(getPara("addDeptId"))) {
            criteria.andAddDeptIdEqualTo(getPara("addDeptId"));
        }
        if (StringUtils.isNotEmpty(getPara("auditState"))) {
            criteria.andAuditStateEqualTo(getParaToInt("auditState"));
        }
    }

    /**
     * 处理工作流开始
     *
     * @param contractorExposure 参数实体
     * @param nextUserId           下个处理人id
     * @throws Exception 异常
     */
    private void handleFlowStart(ContractorExposure contractorExposure, String nextUserId) throws Exception {
        Map<String, String> dataMap = new HashMap<String, String>();
        dataMap.put(FlowDefConstants.FLOW_FIRSTUSER_ID, nextUserId);
        String content = "年度评价流程";
        //启动流程实例
        flowManagementService.flowCreateAndRun(FlowBusinessConstants.BUSINESS_CONTRACTOR_EXPOSURE
                , contractorExposure.getId()
                , content
                , getSessionUser().getName()
                , dataMap);
    }

    /**
     * 处理工作流结束
     *
     * @param request 请求
     * @throws KernelException 内核异常
     */
    private boolean handleFlowEnd(HttpServletRequest request) throws KernelException, NumberFormatException {
        String workItemId = request.getParameter("workItemId");//获取工作项id
        //查询处理结果及意见
        WorkflowReview workflowReview = flowManagementService.getWorkflowReviewByRequest(request, "workflowReview", workItemId);
        //保存处理结果
        boolean boo = flowManagementService.saveWorkflowReview(workflowReview);

        //结束环节，继续流程向下执行
        if (boo) {
            flowManagementService.workItemComplete(workItemId);
            int auditState = Integer.parseInt(request.getParameter("auditState").trim());
            ContractorExposure contractorExposure = new ContractorExposure();
            contractorExposure.setId(request.getParameter("businessId"));
            contractorExposure.setAuditState(auditState);
            contractorExposureService.updateByPrimaryKeySelective(contractorExposure);
            return true;
        }
        return false;
    }
}
